package com.zhang.common.config;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;


/**
 * PropertiesRead
 * 读取 application-(spring.profiles.active).properties 配置
 * 读取方式：PropertiesRead.getProperty("file.attachment.manager");
 * @author zhangxin
 * @date 2021/6/23
 */
public final class PropertiesRead {
    private static String config_file = "application";
    private static Properties prop = null;
    private static boolean loaded = false;
    private static String activeProfile = null;

    private PropertiesRead() {
    }

    private static void initialize() {
        prop = new Properties();

        try {
            InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(config_file + ".properties");
            prop.load(is);
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        String profile = System.getenv("SPRING_PROFILES_ACTIVE");
        if (profile == null || profile.trim().length() == 0) {
            profile = System.getProperty("spring.profiles.active");
        }

        if (profile == null || profile.trim().length() == 0) {
            profile = prop.getProperty("spring.profiles.active");
        }

        if (profile != null && profile.trim().length() > 0) {
            activeProfile = profile.trim();

            try {
                InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(config_file + "-" + profile.trim() + ".properties");
                prop.load(is);
            } catch (Exception var2) {
                var2.printStackTrace();
            }
        }

        loaded = true;
    }

    public static void refresh() {
        prop = null;
        loaded = false;
    }

    public static String getProperty(String key) {
        if (!loaded) {
            initialize();
        }

        return prop.getProperty(key);
    }

    public static Enumeration<String> keys() {
        if (!loaded) {
            initialize();
        }

        return new Enumeration<String>() {
            Enumeration<Object> keys;

            {
                this.keys = PropertiesRead.prop.keys();
            }

            public boolean hasMoreElements() {
                return this.keys.hasMoreElements();
            }

            public String nextElement() {
                return (String)this.keys.nextElement();
            }
        };
    }

    public static String getActiveProfile() {
        if (!loaded) {
            initialize();
        }

        if (activeProfile == null) {
            activeProfile = "";
        }

        return activeProfile;
    }
}

